package org.jeecg.common.util;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

public class WaterMarkUtil {
    /**
     *
     * @param file  文件
     * @param storeFolder  文件存储文件夹
     * @param filePath  文件存储路径
     * @return  返回文件路径
     * @throws Exception
     */
    public static File addWatermark(MultipartFile file, String storeFolder,  String filePath) throws Exception {
        // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
        Image srcImg = ImageIO.read(file.getInputStream());
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        String markText = "湖南新材料研究院";

        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth,
                srcImgHeight,
                BufferedImage.TYPE_INT_RGB);
        //获取 Graphics2D 对象
        Graphics2D g = bufImg.createGraphics();
        //设置绘图区域
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //设置字体

        int size = (int) ((int) srcImgWidth * 0.05);
        Font font = new Font("宋体", Font.PLAIN, Math.max(12,Math.min(40, size)));
        // 根据图片的背景设置水印颜色
        g.setColor(Color.lightGray);
        g.setFont(font);
        //获取文字长度
        int len = g.getFontMetrics(
                g.getFont()).charsWidth(markText.toCharArray(),
                0,
                markText.length());
        int margin = (int) ((int) srcImgWidth * 0.05);
        int x = srcImgWidth - len - Math.max(16,Math.min(32, margin));
        int y = srcImgHeight -Math.max(16,Math.min(32, margin));
        g.drawString(markText, x, y);
        g.dispose();

        // 输出图片
        File waterFile = new File(storeFolder);
        if(!waterFile.exists()) waterFile.mkdirs();

        FileOutputStream outImgStream = new FileOutputStream(filePath);
        ImageIO.write(bufImg, "png", outImgStream);
        outImgStream.flush();
        outImgStream.close();

        return waterFile;

    }
}
